Skip to content

Fix PKCS#11 key lifetime on slot refresh and EC teardown - #697

Open
mtrojnar wants to merge 2 commits into
OpenSC:masterfrom
mtrojnar:fix-694-evp-pkey-cache
Open

mtrojnar wants to merge 2 commits into
OpenSC:masterfrom
mtrojnar:fix-694-evp-pkey-cache

Conversation

@mtrojnar

Copy link
Copy Markdown
Member

Pull Request Type

  • Bug fix

Related Issue

Fixes #694

Current Behavior

Refreshing slots can free the cached EVP_PKEY while a caller still holds a usable RSA key. The next signature can crash when it reads the freed wrapper to determine the RSA size.

New Behavior

RSA signing uses the key OpenSSL already passed in. Retained keys continue to sign after a slot refresh when the token remains available, and repeated key loads still benefit from the cache.

Scope of Changes

Synchronize cache lookup and eviction without holding the cache lock during token operations. Preserve separate wrappers for callers and prevent the cache lock from being inherited locked at fork. A separate commit pairs legacy EC key references with cleanup callbacks on OpenSSL 1.0.2.

Testing

  • Existing tests: make check (49 passed, 5 skipped).
  • Regression coverage added for cached RSA key use after fork and slot refresh; Valgrind reported no errors or leaks on this path.
  • OpenSSL 1.0.2: four EC tests passed; Valgrind confirmed that the EC copy test no longer leaks.

Additional Notes

Stale PKCS#11 handles after logout or session loss remain tracked in #696.

License Declaration

  • I hereby agree to license my contribution under the project's license.

Slot refresh can evict a cached EVP_PKEY while a caller's RSA key still
owns the backing PKCS#11 object. Signing used to look up the freed
wrapper just to obtain the RSA size. Use the RSA key already supplied by
OpenSSL instead.

Keep fast repeated key loads by pinning the cached wrapper during
lookup and detaching it on eviction. Prevent detached objects from
recreating the reference cycle, and release the cache lock in both
processes after a fork.

Fixes OpenSC#694
Legacy ECDSA and ECDH methods lack the finish hook that releases the
backing PKCS#11 object on newer OpenSSL versions. The leaked reference
keeps the object and its slot alive after cache eviction.

Attach the lifetime callbacks to the EC_KEY on OpenSSL 1.0.2. Each
copy takes its own reference, and freeing the key releases it without
leaving callbacks registered globally after libp11 is unloaded.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use-after-free of the cached EVP_PKEY in pkcs11_get_key() after the key cache is wiped

1 participant